
import axios from 'axios'
import qs from 'qs';
import router from '../router'
import store from '../store/index.js'
import {
  MessageBox,
  Message
} from 'element-ui'
import {
  getToken,removeToken,removeUserInfo
} from '@/utils/auth'

let urlArr=[
  '/UserInfo/UserEdit',
  '/UserInfo/UserToAuthor',
  '/ScriptWriting/ScriptWritingEdit',
  '/TradeInfo/TradeInfoAdd',
  '/MediaContent/MediaContentEdit',
  '/News/NewsEdit',
  '/Organ/OrganEdit',
  '/RoyaltyRate/RoyaltyRateEdit',
]
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 创建axios实例
let service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  // timeout: 10000,
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  withCredentials:true,
})

// request拦截器
service.interceptors.request.use(
  config => {
    // if (getToken()) {
    //   config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    // config.headers['userId'] = '38'
    if(urlArr.indexOf(config.url)>-1){
      config.headers['content-type'] = 'application/json'
    }else{
      if(!(config.url.indexOf('UpLoadImg')>-1||config.url.indexOf('UploadFile')>-1)){
        config.data = qs.stringify(config.data)
      }
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(res => {
    let code = res.data.code
    if (code === -1) {
      MessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        removeToken()
        removeUserInfo()
        store.commit("setUser", {});
        router.push({path:'/login'})
      })
    }  else {
      return res.data
    }
  },
  error => {
    let status = error.response.data.code
    let msg = error.response.data.message
    if(status==401){
      MessageBox.confirm(
        '登录状态已过期，请重新登录',
        '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        removeToken()
        router.push({path:'/login'})
      })
    }
    else if (status >= 400) {
      Message({
        message: msg,
        dangerouslyUseHTMLString: true,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      console.log('err' + error)
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
